package com.rexolar.openapi.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rexolar.openapi.bean.*;
import com.rexolar.openapi.bean.request.*;
import com.rexolar.openapi.bean.response.*;
import com.rexolar.openapi.common.OpenApiResult;
import com.rexolar.openapi.constants.ApiConstant;
import com.rexolar.openapi.context.OpenContextUtil;
import com.rexolar.openapi.db.entity.PaasDeviceOptLog;
import com.rexolar.openapi.db.entity.PaasGatewayCredentials;
import com.rexolar.openapi.db.entity.PaasGatewayDeviceRelation;
import com.rexolar.openapi.enums.*;
import com.rexolar.openapi.service.RexolarApiClient;
import com.rexolar.openapi.service.impl.DeviceOptLogService;
import com.rexolar.openapi.service.impl.GatewayCredentialsService;
import com.rexolar.openapi.service.impl.PaasGatewayDeviceRelationService;
import com.rexolar.openapi.utlis.JwtUtils;
import com.rexolar.openapi.utlis.RandomGeneratorUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhusiyu11000
 * @date 2020-01-16
 **/
@Slf4j
@RestController
public class OpenApiController {
    @Autowired
    public RexolarApiClient rexolarApiClient;

    @Autowired
    public GatewayCredentialsService gatewayCredentialsService;

    @Autowired
    public DeviceOptLogService deviceOptLogService;

    @Autowired
    public PaasGatewayDeviceRelationService paasGatewayDeviceRelationService;

    private static final long ONE_DAY_SECONDS = 24 * 60 * 60 * 1000;


    @PostMapping("/createGw")
    @ResponseBody
    @SentinelResource(value = "createGw",blockHandler = "handler_createGw")
    public OpenApiResult createGw(HttpServletRequest request) {
        log.info("createGw ===> gateWayRequest:{}", OpenContextUtil.getContext().getParamsMap());
        GatewayRequest gateWayRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), GatewayRequest.class);
        if(StringUtils.isBlank(gateWayRequest.getGwName())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"gwName");
        }
        if(StringUtils.isBlank(gateWayRequest.getGwAlias())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"gwAlias");
        }
        if(StringUtils.isBlank(gateWayRequest.getProfileId())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"profileId");
        }
        if(gateWayRequest.getGwName().length() > 32){
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_OVERSIZE);
        }
        if(gateWayRequest.getGwAlias().length() > 32){
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_OVERSIZE);
        }

        String token = request.getHeader("token");
        Map payload = JwtUtils.getPayload(token);
        String tenantId = (String) payload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("createGw tenantId is null, gateWayRequest:{}", gateWayRequest);
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        LambdaQueryWrapper<PaasGatewayCredentials> queryWrapper = new LambdaQueryWrapper<PaasGatewayCredentials>();
        queryWrapper.eq(PaasGatewayCredentials::getGwName, gateWayRequest.getGwName());
        queryWrapper.eq(PaasGatewayCredentials::getTenantId, tenantId);
        queryWrapper.ne(PaasGatewayCredentials::getStatus, GwStatusEnum.DELETED.getCode());
        List<PaasGatewayCredentials> list = gatewayCredentialsService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(list)){
            log.error("createGw exist, name:{}", gateWayRequest.getGwName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_GWNAME);
        }

        if(StringUtils.isNotBlank(gateWayRequest.getClientId())){
            if(gateWayRequest.getClientId().length() > 20){
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_CLIENT_ERR);
            }
            LambdaQueryWrapper<PaasGatewayCredentials> clientIdQueryWrapper = new LambdaQueryWrapper<PaasGatewayCredentials>();
            clientIdQueryWrapper.eq(PaasGatewayCredentials::getClientId, gateWayRequest.getClientId());
            clientIdQueryWrapper.eq(PaasGatewayCredentials::getTenantId, tenantId);
            clientIdQueryWrapper.ne(PaasGatewayCredentials::getStatus, GwStatusEnum.DELETED.getCode());
            List<PaasGatewayCredentials> list1 = gatewayCredentialsService.list(clientIdQueryWrapper);
            if(!CollectionUtils.isEmpty(list1)){
                log.error("createGw exist, clientId:{}", gateWayRequest.getClientId());
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_CLIENT_ID);
            }
        }


        DeviceProfileData deviceProfile = rexolarApiClient.getDeviceProfileInfo(gateWayRequest.getProfileId(), token);
        if(deviceProfile==null){
            log.error("createGw deviceProfile not exist, getDeviceProfileInfo profileId:{}", gateWayRequest.getProfileId());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_ProFile_NOT_EXIST);
        }

        DeviceBasicData device = rexolarApiClient.getDeviceByDeviceName(gateWayRequest.getGwName(), token);
        if(device!=null){
            log.warn("createGw exist, getDeviceByDeviceName name:{}", gateWayRequest.getGwName());
            DeviceCredentialsData deviceCredentialsData = rexolarApiClient.getDeviceCredentials(device.getCoreId(), token);
            GatewayResponse gatewayResponse = getGatewayResponse(gateWayRequest, deviceCredentialsData, device.getTenantId());
            if(gatewayResponse==null){
                log.error("createGw getGatewayResponse error, gateWayRequest:{}", gateWayRequest);
                return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
            }
            return OpenApiResult.success(gatewayResponse);

        }else{
            GatewayResponse gatewayResponse = generateGw(gateWayRequest, token);
            if(gatewayResponse==null){
                log.error("createGw error, gateWayRequest:{}", gateWayRequest);
                return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
            }
            return OpenApiResult.success(gatewayResponse);
        }
    }

    private GatewayResponse getGatewayResponse(GatewayRequest gateWayRequest, DeviceCredentialsData deviceCredentialsData, String tenantId) {
        PaasGatewayCredentials entity = new PaasGatewayCredentials();
        entity.setGwId(deviceCredentialsData.getCoreId());
        entity.setGwName(gateWayRequest.getGwName());
        entity.setGwAlias(gateWayRequest.getGwAlias());
        JSONObject jsonObject = JSONObject.parseObject(deviceCredentialsData.getCredentialsValue());

        entity.setClientId(jsonObject.get("clientId").toString());
        entity.setUsername(jsonObject.get("userName").toString());
        entity.setPassword(jsonObject.get("password").toString());
        entity.setTenantId(tenantId);
        entity.setStatus(GwStatusEnum.CREATED.getCode());
        entity.setProfileId(gateWayRequest.getProfileId());
        Date createTime = new Date();
        entity.setGmtCreate(createTime);
        entity.setGmtModified(createTime);

        if(!gatewayCredentialsService.save(entity)){
            log.error("generateGw getGatewayResponse save error, data:{}", entity);
            return null;
        }
        GatewayResponse gatewayResponse = new GatewayResponse();
        gatewayResponse.setClientId(entity.getClientId());
        gatewayResponse.setClientPassword(entity.getPassword());
        gatewayResponse.setClientUsername(entity.getUsername());
        gatewayResponse.setDeviceId(entity.getGwId());
        gatewayResponse.setTenantId(entity.getTenantId());
        gatewayResponse.setGwAlias(gateWayRequest.getGwAlias());
        gatewayResponse.setGwName(gateWayRequest.getGwName());
        return gatewayResponse;
    }

    @PostMapping("/importGws")
    public void importGws(@RequestPart("file") MultipartFile file, HttpServletRequest request) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
        //获取注解的值，跟excel表的表头对应
        Field[] fields = GwCredentials.class.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            String header = fields[i].getDeclaredAnnotation(ApiModelProperty.class).value();
            reader.addHeaderAlias(header, fields[i].getName());
        }

        List<GwCredentials> deviceInfoList = reader.read(0, 1, GwCredentials.class);

//        return this.saveOrUpdateBatch(deviceInfoList);
    }

    private GatewayResponse generateGw(GatewayRequest gateWayRequest, String token) {
        GatewayResponse gatewayResponse = new GatewayResponse();
        DynamicCreateDevice device = new DynamicCreateDevice();
        DynamicCreateDevice.DeviceBean deviceBean = new DynamicCreateDevice.DeviceBean();
        DynamicCreateDevice.DeviceProfileId deviceProfileId = new DynamicCreateDevice.DeviceProfileId();
        DynamicCreateDevice.Credentials mqttBasicCredentials = new DynamicCreateDevice.Credentials();
        DynamicCreateDevice.AdditionalInfo additionalInfo = new DynamicCreateDevice.AdditionalInfo();

        deviceBean.setName(gateWayRequest.getGwName());
        deviceBean.setLabel(gateWayRequest.getGwAlias());
        deviceProfileId.setId(gateWayRequest.getProfileId());
        deviceBean.setDeviceProfileId(deviceProfileId);
        additionalInfo.setGateway(true);
        additionalInfo.setOverwriteActivityTime(true);
        deviceBean.setAdditionalInfo(additionalInfo);

        DynamicCreateDevice.CredentialsValue credentialsValue = new DynamicCreateDevice.CredentialsValue();
        if(StringUtils.isBlank(gateWayRequest.getClientId())){
            String clientId = RandomGeneratorUtils.generateRandomString(12);
            credentialsValue.setClientId(clientId);
        }else {
            credentialsValue.setClientId(gateWayRequest.getClientId());
        }
        if(StringUtils.isBlank(gateWayRequest.getUserName())){
            String username = RandomGeneratorUtils.generateRandomString(10);
            credentialsValue.setUserName(username);
        }else {
            credentialsValue.setUserName(gateWayRequest.getUserName());
        }
        if(StringUtils.isBlank(gateWayRequest.getUserName())){
            String password = RandomGeneratorUtils.generateRandomString(20);
            credentialsValue.setPassword(password);
        }else {
            credentialsValue.setPassword(gateWayRequest.getPassword());
        }


        mqttBasicCredentials.setCredentialsValue(JSON.toJSONString(credentialsValue));

        device.setDevice(deviceBean);
        device.setCredentials(mqttBasicCredentials);

        String data = JSON.toJSONString(device);
        CreateGwRsp result = rexolarApiClient.dynamicCreateDevice(data, token);
        if(result==null){
            log.error("generateGw dynamicCreateDevice error, data:{}", data);
            return null;
        }
        PaasGatewayCredentials entity = new PaasGatewayCredentials();
        entity.setGwId(result.getId());
        entity.setGwName(gateWayRequest.getGwName());
        entity.setGwAlias(gateWayRequest.getGwAlias());
        entity.setClientId(credentialsValue.getClientId());
        entity.setUsername(credentialsValue.getUserName());
        entity.setPassword(credentialsValue.getPassword());
        entity.setTenantId(result.getTenantId());
        entity.setStatus(GwStatusEnum.CREATED.getCode());
        entity.setProfileId(gateWayRequest.getProfileId());
        Date createTime = new Date();
        entity.setGmtCreate(createTime);
        entity.setGmtModified(createTime);

        if(!gatewayCredentialsService.save(entity)){
            log.error("generateGw gatewayCredentialsService save error, data:{}", data);
            return null;
        }

        gatewayResponse.setClientId(credentialsValue.getClientId());
        gatewayResponse.setClientPassword(credentialsValue.getPassword());
        gatewayResponse.setClientUsername(credentialsValue.getUserName());
        gatewayResponse.setDeviceId(result.getId());
        gatewayResponse.setTenantId(result.getTenantId());
        gatewayResponse.setGwAlias(gateWayRequest.getGwAlias());
        gatewayResponse.setGwName(gateWayRequest.getGwName());
        return gatewayResponse;
    }

    @PostMapping("/applyGws")
    @ResponseBody
    public OpenApiResult applyGws(HttpServletRequest request) {
        log.info("applyGws ===> gwApplyRequest:{}", OpenContextUtil.getContext().getParamsMap());
        GwApplyRequest gwApplyRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), GwApplyRequest.class);
        if(StringUtils.isBlank(gwApplyRequest.getProfileId())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"profileId");
        }
        if(gwApplyRequest.getNum()==null){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"num");
        }
        if(gwApplyRequest.getNum() > 100){
            log.error("applyGws 一次申请个数大于100, gateWayRequest:{}", gwApplyRequest);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_GW_NUM_OVERSIZE);
        }
        String token = request.getHeader("token");
        Map payload = JwtUtils.getPayload(token);
        String tenantId = (String) payload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("applyGws tenantId is null, gwApplyRequest:{}", gwApplyRequest);
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        DeviceProfileData deviceProfile = rexolarApiClient.getDeviceProfileInfo(gwApplyRequest.getProfileId(), token);
        if(deviceProfile==null){
            log.error("applyGws deviceProfile not exist, getDeviceProfileInfo profileId:{}", gwApplyRequest.getProfileId());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_ProFile_NOT_EXIST);
        }
        List<GatewayResponse> gatewayResponse = new ArrayList<>();
        LambdaQueryWrapper<PaasGatewayCredentials> queryWrapper = new LambdaQueryWrapper<PaasGatewayCredentials>();
        queryWrapper.eq(PaasGatewayCredentials::getStatus, GwStatusEnum.CREATED.getCode());
        queryWrapper.eq(PaasGatewayCredentials::getProfileId, gwApplyRequest.getProfileId());
        queryWrapper.eq(PaasGatewayCredentials::getTenantId, tenantId);
        List<PaasGatewayCredentials> list = gatewayCredentialsService.list(queryWrapper);
        int newNum = 0;
        if(list.size() > gwApplyRequest.getNum()){
            List<PaasGatewayCredentials> subList = list.subList(0, gwApplyRequest.getNum());
            for(PaasGatewayCredentials item: subList){
                GatewayResponse gatewayResponseItem = new GatewayResponse();
                BeanUtils.copyProperties(item, gatewayResponseItem);
                gatewayResponseItem.setDeviceId(item.getGwId());
                gatewayResponseItem.setGwAlias(item.getGwAlias());
                gatewayResponseItem.setClientUsername(item.getUsername());
                gatewayResponseItem.setClientPassword(item.getPassword());
                gatewayResponse.add(gatewayResponseItem);
            }
            return OpenApiResult.success(gatewayResponse);
        }else {
            for(PaasGatewayCredentials item: list){
                GatewayResponse gatewayResponseItem = new GatewayResponse();
                BeanUtils.copyProperties(item, gatewayResponseItem);
                gatewayResponseItem.setDeviceId(item.getGwId());
                gatewayResponseItem.setGwAlias(item.getGwAlias());
                gatewayResponseItem.setClientUsername(item.getUsername());
                gatewayResponseItem.setClientPassword(item.getPassword());
                gatewayResponse.add(gatewayResponseItem);
            }
            newNum = gwApplyRequest.getNum() - list.size();
            for(int i = 0; i < newNum; i++){
                String gwName = "gw-" + RandomGeneratorUtils.generateRandomString(10);
                GatewayRequest gateWayRequest = new GatewayRequest();
                gateWayRequest.setGwName(gwName);
                gateWayRequest.setGwAlias(gwName);
                gateWayRequest.setProfileId(gwApplyRequest.getProfileId());
                GatewayResponse result = generateGw(gateWayRequest, token);
                if(result==null){
                    log.error("applyGws generateGw error, gateWayRequest:{}", gateWayRequest);
                    continue;
                }
                gatewayResponse.add(result);
            }
        }

        if(CollectionUtils.isEmpty(gatewayResponse)){
            log.error("applyGws generateGw error, gateWayRequest:{}", gwApplyRequest);
            return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
        }
        return OpenApiResult.success(gatewayResponse);
    }
    @PostMapping("/inactiveGwList")
    @ResponseBody
    public OpenApiResult inactiveGwList(HttpServletRequest request) {
        log.info("inactiveGwList ===> inactiveGwRequest:{}", OpenContextUtil.getContext().getParamsMap());
        InactiveGwRequest inactiveGwRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), InactiveGwRequest.class);
        if(inactiveGwRequest==null){
            log.error("inactiveGwList 缺少必选参数, inactiveGwRequest:{}", inactiveGwRequest);
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS);
        }
        if(inactiveGwRequest.getPageNo()==null || inactiveGwRequest.getPageNo() < 0){
            inactiveGwRequest.setPageNo(1);
        }
        if(inactiveGwRequest.getPageSize()==null || inactiveGwRequest.getPageSize()<= 0|| inactiveGwRequest.getPageSize() > 100){
            inactiveGwRequest.setPageSize(20);
        }

        String token = request.getHeader("token");
        Map payload = JwtUtils.getPayload(token);
        String tenantId = (String) payload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("inactiveGwList tenantId is null");
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }

        List<GatewayResponse> gatewayResponse = new ArrayList<>();
        IPage<PaasGatewayCredentials> result = gatewayCredentialsService.selectPage(inactiveGwRequest, tenantId);
        result.getRecords().forEach(item->{
            GatewayResponse gatewayResponseItem = new GatewayResponse();
            BeanUtils.copyProperties(item, gatewayResponseItem);
            gatewayResponseItem.setDeviceId(item.getGwId());
            gatewayResponseItem.setGwAlias(item.getGwAlias());
            gatewayResponseItem.setClientUsername(item.getUsername());
            gatewayResponseItem.setClientPassword(item.getPassword());
            gatewayResponse.add(gatewayResponseItem);
        });
        return OpenApiResult.success(new InactiveGwResponse(inactiveGwRequest.getPageNo(), inactiveGwRequest.getPageSize(), result.getTotal(), gatewayResponse));
    }

    @SentinelResource(value="permitAllJoin")
    @PostMapping("/permitAllJoin")
    @ResponseBody
    public OpenApiResult permitAllJoin(HttpServletRequest request) {
        log.info("permitAllJoin ===> permitAllJoinRequest:{}", OpenContextUtil.getContext().getParamsMap());
        PermitAllJoinRequest permitAllJoinRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), PermitAllJoinRequest.class);
        if(permitAllJoinRequest==null || StringUtils.isBlank(permitAllJoinRequest.getGwName())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"gwName");
        }
        String token = request.getHeader("token");
        Map payload = JwtUtils.getPayload(token);
        String tenantId = (String) payload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("permitAllJoin tenantId is null, permitAllJoinRequest:{}", permitAllJoinRequest);
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        LambdaQueryWrapper<PaasGatewayCredentials> queryWrapper = new LambdaQueryWrapper<PaasGatewayCredentials>();
        queryWrapper.eq(PaasGatewayCredentials::getGwName, permitAllJoinRequest.getGwName());
        queryWrapper.eq(PaasGatewayCredentials::getStatus, GwStatusEnum.ON.getCode());
        queryWrapper.eq(PaasGatewayCredentials::getTenantId, tenantId);
        PaasGatewayCredentials paasGatewayCredentials = gatewayCredentialsService.getOne(queryWrapper);
        if(paasGatewayCredentials==null){
            log.error("permitAllJoin gw not exist, gwName:{}", permitAllJoinRequest.getGwName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_GW_NOT_EXIST);
        }

        boolean result = gatewayCredentialsService.permitAllJoin(paasGatewayCredentials, token);
        if(!result){
            log.error("permitAllJoin error, permitAllJoinRequest:{}", permitAllJoinRequest);
        }else {
            PaasDeviceOptLog deviceOptLog = new PaasDeviceOptLog();
            deviceOptLog.setDeviceId(paasGatewayCredentials.getGwId());
            deviceOptLog.setDeviceName(permitAllJoinRequest.getGwName());
            deviceOptLog.setType(DeviceOptTypeEnum.GW_ON.getCode());
            deviceOptLog.setContent("gateway premit join");
            deviceOptLog.setStatus(1);
            deviceOptLog.setGmtModified(new Date());
            deviceOptLog.setGmtCreate(new Date());
            if(!deviceOptLogService.save(deviceOptLog)){
                log.error("permitAllJoin optlog save error, deviceOptLog:{}", deviceOptLog);
            }
        }
        return OpenApiResult.success(result);
    }

    @PostMapping("/device/list")
    @ResponseBody
    public OpenApiResult deviceList(HttpServletRequest request) {
        log.info("deviceList ===> deviceListRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DevicePageRequest devicePageRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DevicePageRequest.class);

        if(devicePageRequest ==null){
            log.error("deviceList 缺少必选参数, deviceListRequest:{}", devicePageRequest);
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS);
        }
        if(devicePageRequest.getPageNo()==null || devicePageRequest.getPageNo() < 0){
            devicePageRequest.setPageNo(0);
        }
        if(devicePageRequest.getPageSize()==null || devicePageRequest.getPageSize()<= 0|| devicePageRequest.getPageSize() > 100){
            devicePageRequest.setPageSize(20);
        }
        String token = request.getHeader("token");
        PageResult data = rexolarApiClient.getTenantDevices(token, devicePageRequest.getPageNo(), devicePageRequest.getPageSize());
        return OpenApiResult.success(data);
    }

    @PostMapping("/device/lastest/timeSeries")
    @ResponseBody
    public OpenApiResult deviceLastestTimeSeries(HttpServletRequest request) {
        log.info("deviceLastestTimeSeries ===> deviceDatasRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DeviceDatasRequest deviceDatasRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DeviceDatasRequest.class);
        if(StringUtils.isBlank(deviceDatasRequest.getDeviceNames())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceNames");
        }
        String[] deviceNames = deviceDatasRequest.getDeviceNames().split(",");
        if(deviceNames.length > 50){
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_OVERSIZE);
        }
        String token = request.getHeader("token");
        Map payload = JwtUtils.getPayload(token);
        String tenantId = (String) payload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("deviceLastestTimeSeries tenantId is null, deviceDatasRequest:{}", deviceDatasRequest);
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        List<DeviceTimeSeriesResponse> responseList = new ArrayList<>();
        for(String deviceName : deviceNames){
//            LambdaQueryWrapper<PaasGatewayDeviceRelation> query = new LambdaQueryWrapper<>();
//            query.in(PaasGatewayDeviceRelation::getDeviceName, deviceName);
//            query.eq(PaasGatewayDeviceRelation::getStatus, GwDeviceStatusEnum.ON.getCode());
//            query.eq(PaasGatewayDeviceRelation::getTenantId, tenantId);
//            List<PaasGatewayDeviceRelation> deviceRelations = paasGatewayDeviceRelationService.list(query);
//            if(CollectionUtils.isEmpty(deviceRelations)){
//                log.error("deviceLastestTimeSeries ILLEGAL_DEVICE_GW_NOT_EXIST, query:{}", deviceDatasRequest.getDeviceNames());
//                continue;
//            }
//            String deviceId = deviceRelations.get(0).getDeviceId();

            DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(deviceName, token);
            if(deviceBasicData==null){
                log.error("deviceLastestTimeSeries ILLEGAL_DEVICE_NOT_EXIST, deviceName:{}", deviceName);
                continue;
            }
            String deviceId = deviceBasicData.getCoreId();
            Map<String, List<DeviceTimeSeries>> list = rexolarApiClient.getDeviceTimeSeriesLatest(deviceId, token, new String[]{}, true);
            DeviceTimeSeriesResponse deviceTimeSeriesResponse = new DeviceTimeSeriesResponse();
            deviceTimeSeriesResponse.setDeviceId(deviceId);
            deviceTimeSeriesResponse.setDeviceName(deviceName);
            deviceTimeSeriesResponse.setType(DeviceTypeEnum.DEVICE.getCode());
            List<TimeSeriesResponse> timeSeries = new ArrayList<>();
            for(String key : list.keySet()){
                TimeSeriesResponse timeSeriesResponse = new TimeSeriesResponse();
                List<DeviceTimeSeries> deviceTimeSeriesList = list.get(key);
                for(DeviceTimeSeries deviceTimeSeries : deviceTimeSeriesList){
                    String recordTime = DateUtil.formatDateTime(new Date(Long.parseLong(deviceTimeSeries.getTs())));
                    timeSeriesResponse.setRecordTime(recordTime);
                    timeSeriesResponse.setKey(key);
                    timeSeriesResponse.setValue(deviceTimeSeries.getValue());
                }
                timeSeries.add(timeSeriesResponse);
            }
            deviceTimeSeriesResponse.setTimeSeries(timeSeries);
            responseList.add(deviceTimeSeriesResponse);
        }

        return OpenApiResult.success(responseList);
    }

    @PostMapping("/device/attributes")
    @ResponseBody
    public OpenApiResult deviceAttributes(HttpServletRequest request) {
        log.info("deviceAttributes ===> deviceDatasRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DeviceDatasRequest deviceDatasRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DeviceDatasRequest.class);
        if(StringUtils.isBlank(deviceDatasRequest.getDeviceNames())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceNames");
        }
        String[] deviceNames = deviceDatasRequest.getDeviceNames().split(",");
        if(deviceNames.length > 50){
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_OVERSIZE);
        }
        String token = request.getHeader("token");
        Map payload = JwtUtils.getPayload(token);
        String tenantId = (String) payload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("deviceAttributes tenantId is null, deviceDatasRequest:{}", deviceDatasRequest);
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        List<DeviceAttributesResponse> responseList = new ArrayList<>();
        for(String deviceName : deviceNames){
            DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(deviceName, token);
            if(deviceBasicData==null){
                log.error("deviceAttributes ILLEGAL_DEVICE_NOT_EXIST, deviceName:{}", deviceName);
                continue;
            }
            DeviceProfileData deviceProfileData = rexolarApiClient.getDeviceProfileInfo(deviceBasicData.getDeviceProfileId(), token);
            if(deviceProfileData.getName().equals("lightDevice") || deviceProfileData.getName().equals("gateway-zigbee")){
                Map<String, Object> attributes = rexolarApiClient.getDeviceAttributes(deviceBasicData.getCoreId(), token, new String[]{});
                if(attributes.isEmpty()){
                    log.error("deviceAttributes deviceId:{} getDeviceAttributes not found", deviceBasicData.getCoreId());
                    continue;
                }
                DeviceAttributesResponse deviceAttributesResponse = new DeviceAttributesResponse();
                deviceAttributesResponse.setDeviceId(deviceBasicData.getCoreId());
                deviceAttributesResponse.setDeviceName(deviceBasicData.getName());
                deviceAttributesResponse.setLastConnectTime(attributes.get("lastConnectTime")==null?
                        null: DateUtil.formatDateTime(new Date(Long.parseLong(attributes.get("lastConnectTime").toString()))));
                deviceAttributesResponse.setLastActivityTime(attributes.get("lastActivityTime")==null?
                        null: DateUtil.formatDateTime(new Date(Long.parseLong(attributes.get("lastActivityTime").toString()))));
                deviceAttributesResponse.setStatus(attributes.get("active")==null?"false":attributes.get("active").toString());
                deviceAttributesResponse.setMAC(deviceBasicData.getName());
                responseList.add(deviceAttributesResponse);
            }else {
                LambdaQueryWrapper<PaasGatewayDeviceRelation> query = new LambdaQueryWrapper<>();
                query.in(PaasGatewayDeviceRelation::getDeviceName, deviceName);
                query.in(PaasGatewayDeviceRelation::getTenantId, tenantId);
                query.eq(PaasGatewayDeviceRelation::getStatus, GwDeviceStatusEnum.ON.getCode());
                List<PaasGatewayDeviceRelation> deviceRelations = paasGatewayDeviceRelationService.list(query);
                if(CollectionUtils.isEmpty(deviceRelations)){
                    log.error("deviceAttributes ILLEGAL_DEVICE_GW_NOT_EXIST, query:{}", deviceName);
                    continue;
                }
                Map<String, String> idNameMap = deviceRelations.stream().collect(Collectors.toMap(PaasGatewayDeviceRelation::getDeviceId, PaasGatewayDeviceRelation::getDeviceName));
                for(String deviceId : idNameMap.keySet()){
                    Map<String, Object> attributes = rexolarApiClient.getDeviceAttributes(deviceId, token, new String[]{});
                    if(attributes.isEmpty()){
                        log.error("deviceAttributes deviceId:{} getDeviceAttributes type not found", deviceId);
                        continue;
                    }
                    DeviceAttributesResponse deviceAttributesResponse = new DeviceAttributesResponse();
                    deviceAttributesResponse.setDeviceId(deviceId);
                    deviceAttributesResponse.setDeviceName(idNameMap.get(deviceId));
                    deviceAttributesResponse.setLastConnectTime(attributes.get("lastConnectTime")==null?
                            null: DateUtil.formatDateTime(new Date(Long.parseLong(attributes.get("lastConnectTime").toString()))));
                    deviceAttributesResponse.setLastActivityTime(attributes.get("lastActivityTime")==null?
                            null: DateUtil.formatDateTime(new Date(Long.parseLong(attributes.get("lastActivityTime").toString()))));
                    deviceAttributesResponse.setStatus(attributes.get("active")==null?"false":attributes.get("active").toString());
                    deviceAttributesResponse.setMAC(idNameMap.get(deviceId));
                    responseList.add(deviceAttributesResponse);
                }
            }
        }

        return OpenApiResult.success(responseList);
    }

    @PostMapping("/device/timeSeries")
    @ResponseBody
    public OpenApiResult deviceTimeSeries(HttpServletRequest request) {
        log.info("deviceTimeSeries ===> deviceTimeSeriesRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DeviceTimeSeriesRequest deviceTimeSeriesRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DeviceTimeSeriesRequest.class);
        List<DeviceTimeSeriesResponse> responseList = new ArrayList<>();
        if(StringUtils.isBlank(deviceTimeSeriesRequest.getStartTime())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"startTime");
        }
        if(StringUtils.isBlank(deviceTimeSeriesRequest.getEndTime())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"endTime");
        }
        if(StringUtils.isBlank(deviceTimeSeriesRequest.getDeviceName())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceName");
        }

        String token = request.getHeader("token");
        DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(deviceTimeSeriesRequest.getDeviceName(), token);
        if(deviceBasicData==null){
            log.error("deviceTimeSeries deviceName:{} getDeviceByDeviceName type not found", deviceTimeSeriesRequest.getDeviceName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
        }

        try {
            DateTime startTime = DateUtil.parseDateTime(deviceTimeSeriesRequest.getStartTime());
            DateTime endTime = DateUtil.parseDateTime(deviceTimeSeriesRequest.getEndTime());
            if(startTime.equals(endTime) || startTime.isAfter(endTime)){
                log.error("deviceTimeSeries startTime and endTime error, deviceTimeSeriesRequest:{}", deviceTimeSeriesRequest);
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_TIME_RANGE);
            }
            long start = startTime.getTime();
            long end = endTime.getTime();
            if(end - start > 86400000){
                log.error("deviceTimeSeries startTime and endTime error, deviceTimeSeriesRequest:{}", deviceTimeSeriesRequest);
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_TIME_RANGE_OVERSIZE);
            }

            String deviceId = deviceBasicData.getCoreId();

            Map<String, List<DeviceTimeSeries>> list = rexolarApiClient.getDeviceTimeSeriesLatest(deviceId, token, new String[]{}, true);
            if(list.isEmpty()){
                log.error("deviceTimeSeries deviceId:{} getDeviceTimeSeriesLatest type not found", deviceId);
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
            }

            String[] keys = new String[list.keySet().size()];
            list.keySet().toArray(keys);

            Map<String, List<DeviceTimeSeries>> dataList = rexolarApiClient.getDeviceTimeSeries(
                    deviceId, token, keys, start, end, 1000, true, 10000L, null, false);

            DeviceTimeSeriesResponse deviceTimeSeriesResponse = new DeviceTimeSeriesResponse();
            deviceTimeSeriesResponse.setDeviceId(deviceId);
            deviceTimeSeriesResponse.setDeviceName(deviceTimeSeriesRequest.getDeviceName());
            deviceTimeSeriesResponse.setType(DeviceTypeEnum.DEVICE.getCode());
            List<TimeSeriesResponse> timeSeries = new ArrayList<>();
            for(String key : dataList.keySet()){
                List<DeviceTimeSeries> deviceTimeSeriesList = dataList.get(key);
                for(DeviceTimeSeries deviceTimeSeries : deviceTimeSeriesList){
                    TimeSeriesResponse timeSeriesResponse = new TimeSeriesResponse();
                    String recordTime = DateUtil.formatDateTime(new Date(Long.parseLong(deviceTimeSeries.getTs())));
                    timeSeriesResponse.setRecordTime(recordTime);
                    timeSeriesResponse.setKey(key);
                    timeSeriesResponse.setValue(deviceTimeSeries.getValue());
                    timeSeries.add(timeSeriesResponse);
                }
            }
            deviceTimeSeriesResponse.setTimeSeries(timeSeries);
            responseList.add(deviceTimeSeriesResponse);
        }catch (Exception e){
            log.error("deviceTimeSeries error, deviceTimeSeriesRequest:{}", deviceTimeSeriesRequest, e);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_TIME_FORMAT);
        }
        return OpenApiResult.success(responseList);
    }
    @PostMapping("/light/writeProperties")    @ResponseBody
    public OpenApiResult lightWriteProperties(HttpServletRequest request) {
        log.info("lightWriteProperties ===> deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
        WritePropertiesRequest writePropertiesRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), WritePropertiesRequest.class);

        if(StringUtils.isBlank(writePropertiesRequest.getDeviceName())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceName");
        }
        if(StringUtils.isBlank(writePropertiesRequest.getCommand())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"command");
        }
        String token = request.getHeader("token");
        Map tokenPayload = JwtUtils.getPayload(token);
        String tenantId = (String) tokenPayload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("lightWriteProperties tenantId is null,deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(writePropertiesRequest.getDeviceName(), token);
        if(deviceBasicData==null){
            log.error("lightWriteProperties deviceName:{} getDeviceByDeviceName type not found", writePropertiesRequest.getDeviceName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
        }

        JSONObject cmd = new JSONObject();
        try {
            cmd = JSONObject.parseObject(writePropertiesRequest.getCommand());
        }catch (Exception e){
            log.error("lightWriteProperties ILLEGAL_PARAMETERS_JSON_ERROR, writePropertiesRequest:{}", writePropertiesRequest, e);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_JSON_ERROR);
        }

        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("Version", "1.0");
        dataMap.put("VendorCode", "Rexense");
        String time = String.valueOf(System.currentTimeMillis());
        dataMap.put("Timestamp", time);
        dataMap.put("Seq", writePropertiesRequest.getDeviceName() + "-" + time);
        dataMap.put("DeviceId", writePropertiesRequest.getDeviceName());
        dataMap.put("FunctionCode", "WriteLightDevPropertyList");
        dataMap.put("WriteList", cmd);

        boolean result = rexolarApiClient.updateDeviceAttributes(deviceBasicData.getCoreId(), ApiConstant.SHARED_SCOPE, JSON.toJSONString(dataMap), token);
        if(!result){
            log.error("lightWriteProperties error, writePropertiesRequest:{}", writePropertiesRequest);
            return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
        }else{
            PaasDeviceOptLog deviceOptLog = new PaasDeviceOptLog();
            deviceOptLog.setDeviceId(deviceBasicData.getCoreId());
            deviceOptLog.setDeviceName(writePropertiesRequest.getDeviceName());
            deviceOptLog.setType(DeviceOptTypeEnum.DEVICE_RPC.getCode());
            deviceOptLog.setContent(writePropertiesRequest.getCommand());
            deviceOptLog.setStatus(1);
            deviceOptLog.setTenantId(tenantId);
            deviceOptLog.setGmtModified(new Date());
            deviceOptLog.setGmtCreate(new Date());
            if(!deviceOptLogService.save(deviceOptLog)){
                log.error("lightWriteProperties optlog save error, deviceOptLog:{}", deviceOptLog);
            }
        }
        return OpenApiResult.success(dataMap.get("Seq"));
    }
    @PostMapping("/device/writeProperties")    @ResponseBody
    public OpenApiResult writeProperties(HttpServletRequest request) {
        log.info("writeProperties ===> deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
        WritePropertiesRequest writePropertiesRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), WritePropertiesRequest.class);

        if(StringUtils.isBlank(writePropertiesRequest.getDeviceName())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceName");
        }
        if(StringUtils.isBlank(writePropertiesRequest.getCommand())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"command");
        }
        JSONObject cmd = new JSONObject();
        try {
            cmd = JSONObject.parseObject(writePropertiesRequest.getCommand());
        }catch (Exception e){
            log.error("writeProperties ILLEGAL_PARAMETERS_JSON_ERROR, writePropertiesRequest:{}", writePropertiesRequest, e);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_JSON_ERROR);
        }

        String token = request.getHeader("token");
        Map tokenPayload = JwtUtils.getPayload(token);
        String tenantId = (String) tokenPayload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("writeProperties tenantId is null,deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(writePropertiesRequest.getDeviceName(), token);
        if(deviceBasicData==null){
            log.error("writeProperties deviceName:{} getDeviceByDeviceName type not found", writePropertiesRequest.getDeviceName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
        }
        String time = String.valueOf(System.currentTimeMillis());
        //兼容致诚原灯控逻辑
        DeviceProfileData deviceProfileData = rexolarApiClient.getDeviceProfileInfo(deviceBasicData.getDeviceProfileId(), token);
        if(deviceProfileData!=null && "lightDevice".equals(deviceProfileData.getName())){
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("Timestamp", time);
            dataMap.put("Seq", writePropertiesRequest.getDeviceName() + "-" + time);
            dataMap.put("DeviceId", writePropertiesRequest.getDeviceName());
            dataMap.put("FunctionCode", "WriteLightDevPropertyList");
            dataMap.put("WriteList", cmd);
            boolean result = rexolarApiClient.updateDeviceAttributes(deviceBasicData.getCoreId(), ApiConstant.SHARED_SCOPE, JSON.toJSONString(dataMap), token);
            if(!result){
                log.error("writeProperties  lightDevice error, writePropertiesRequest:{}", writePropertiesRequest);
                return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
            }else{
                PaasDeviceOptLog deviceOptLog = new PaasDeviceOptLog();
                deviceOptLog.setDeviceId(deviceBasicData.getCoreId());
                deviceOptLog.setDeviceName(writePropertiesRequest.getDeviceName());
                deviceOptLog.setType(DeviceOptTypeEnum.DEVICE_RPC.getCode());
                deviceOptLog.setContent(writePropertiesRequest.getCommand());
                deviceOptLog.setStatus(1);
                deviceOptLog.setTenantId(tenantId);
                deviceOptLog.setGmtModified(new Date());
                deviceOptLog.setGmtCreate(new Date());
                if(!deviceOptLogService.save(deviceOptLog)){
                    log.error("lightDevice optlog save error, deviceOptLog:{}", deviceOptLog);
                }
            }
            return OpenApiResult.success(dataMap.get("Seq"));

        }else {
            List<DeviceBasicData> gws = rexolarApiClient.getFromRelationsInfo(token, deviceBasicData.getCoreId());
            if(CollectionUtils.isEmpty(gws)){
                log.error("writeProperties gws is empty, deviceId:{}", deviceBasicData.getCoreId());
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_GW_NOT_EXIST);
            }
            String gwId = gws.get(0).getCoreId();
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("Version", "1.0");
            dataMap.put("VendorCode", "Rexense");
            dataMap.put("Timestamp", time);
            dataMap.put("Seq", writePropertiesRequest.getDeviceName() + "-" + time);
            dataMap.put("DeviceId", gws.get(0).getName());
            dataMap.put("FunctionCode", "WriteDevPropertyList");
            HashMap<String, Object> payloadMap = new HashMap<>();
            payloadMap.put("DeviceId", deviceBasicData.getName());
            payloadMap.put("GroupId", "0");
            payloadMap.put("WriteList", cmd);
            dataMap.put("Payload", payloadMap);

            boolean result = rexolarApiClient.updateDeviceAttributes(gwId, ApiConstant.SHARED_SCOPE, JSON.toJSONString(dataMap), token);
            if(!result){
                log.error("writeProperties error, writePropertiesRequest:{}", writePropertiesRequest);
                return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
            }else{
                PaasDeviceOptLog deviceOptLog = new PaasDeviceOptLog();
                deviceOptLog.setDeviceId(deviceBasicData.getCoreId());
                deviceOptLog.setDeviceName(writePropertiesRequest.getDeviceName());
                deviceOptLog.setType(DeviceOptTypeEnum.DEVICE_RPC.getCode());
                deviceOptLog.setContent(writePropertiesRequest.getCommand());
                deviceOptLog.setStatus(1);
                deviceOptLog.setTenantId(tenantId);
                deviceOptLog.setGmtModified(new Date());
                deviceOptLog.setGmtCreate(new Date());
                if(!deviceOptLogService.save(deviceOptLog)){
                    log.error("writeProperties optlog save error, deviceOptLog:{}", deviceOptLog);
                }
            }
            return OpenApiResult.success(dataMap.get("Seq"));
        }
    }

    @PostMapping("/light/command")    @ResponseBody
    public OpenApiResult lightCommand(HttpServletRequest request) {
        log.info("lightCommand ===> lightCommandRequest:{}", OpenContextUtil.getContext().getParamsMap());
        LightCommandRequest lightCommandRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), LightCommandRequest.class);

        if(StringUtils.isBlank(lightCommandRequest.getDeviceName())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceName");
        }
        if(StringUtils.isBlank(lightCommandRequest.getCommand())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"command");
        }
        String token = request.getHeader("token");
        Map tokenPayload = JwtUtils.getPayload(token);
        String tenantId = (String) tokenPayload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("lightCommand tenantId is null,deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(lightCommandRequest.getDeviceName(), token);
        if(deviceBasicData==null){
            log.error("lightCommand deviceName:{} getDeviceByDeviceName type not found", lightCommandRequest.getDeviceName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
        }
        JSONObject cmd = new JSONObject();
        try {
            cmd = JSONObject.parseObject(lightCommandRequest.getCommand());
        }catch (Exception e){
            log.error("lightCommand ILLEGAL_PARAMETERS_JSON_ERROR, lightCommandRequest:{}", lightCommandRequest, e);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_JSON_ERROR);
        }

        boolean result = rexolarApiClient.updateDeviceAttributes(deviceBasicData.getCoreId(), ApiConstant.SHARED_SCOPE, JSON.toJSONString(cmd), token);
        if(!result){
            log.error("lightCommand error, lightCommandRequest:{}", lightCommandRequest);
            return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
        }else{
            PaasDeviceOptLog deviceOptLog = new PaasDeviceOptLog();
            deviceOptLog.setDeviceId(deviceBasicData.getCoreId());
            deviceOptLog.setDeviceName(lightCommandRequest.getDeviceName());
            deviceOptLog.setType(DeviceOptTypeEnum.DEVICE_RPC.getCode());
            deviceOptLog.setContent(lightCommandRequest.getCommand());
            deviceOptLog.setStatus(1);
            deviceOptLog.setTenantId(tenantId);
            deviceOptLog.setGmtModified(new Date());
            deviceOptLog.setGmtCreate(new Date());
            if(!deviceOptLogService.save(deviceOptLog)){
                log.error("lightCommand optlog save error, deviceOptLog:{}", deviceOptLog);
            }
        }
        return OpenApiResult.success(true);

    }

    @PostMapping("/device/rpc")
    @ResponseBody
    public OpenApiResult deviceRpc(HttpServletRequest request) {
        log.info("deviceRpc ===> deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DeviceRpcRequest deviceRpcRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DeviceRpcRequest.class);

        if(StringUtils.isBlank(deviceRpcRequest.getDeviceName())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceName");
        }
        if(StringUtils.isBlank(deviceRpcRequest.getCommand())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"command");
        }

        String token = request.getHeader("token");
        Map tokenPayload = JwtUtils.getPayload(token);
        String tenantId = (String) tokenPayload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("deviceRpc tenantId is null,deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(deviceRpcRequest.getDeviceName(), token);
        if(deviceBasicData==null){
            log.error("deviceRpc deviceName:{} getDeviceByDeviceName type not found", deviceRpcRequest.getDeviceName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
        }
        List<DeviceBasicData> gws = rexolarApiClient.getFromRelationsInfo(token, deviceBasicData.getCoreId());
        if(CollectionUtils.isEmpty(gws)){
            log.error("deviceRpc gws is empty, deviceId:{}", deviceBasicData.getCoreId());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_GW_NOT_EXIST);
        }

        String gwId = gws.get(0).getCoreId();
        JSONObject cmd = new JSONObject();
        try {
            cmd = JSONObject.parseObject(deviceRpcRequest.getCommand());
            cmd.computeIfAbsent("DeviceId", k -> deviceBasicData.getName());
        }catch (Exception e){
            log.error("deviceRpc ILLEGAL_PARAMETERS_JSON_ERROR, deviceRpcRequest:{}", deviceRpcRequest, e);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_PARAMETERS_JSON_ERROR);
        }

        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("Version", "1.0");
        dataMap.put("VendorCode", "Rexense");
        String time = String.valueOf(System.currentTimeMillis());
        dataMap.put("Timestamp", time);
        dataMap.put("Seq", deviceRpcRequest.getDeviceName() + "-" + time);
        dataMap.put("DeviceId", gws.get(0).getName());
        dataMap.put("FunctionCode", deviceRpcRequest.getFunctionCode());
        dataMap.put("Payload", cmd);

        boolean result = rexolarApiClient.updateDeviceAttributes(gwId, ApiConstant.SHARED_SCOPE, JSON.toJSONString(dataMap), token);
        if(!result){
            log.error("deviceRpc error, deviceRpcRequest:{}", deviceRpcRequest);
            return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
        }else{
            PaasDeviceOptLog deviceOptLog = new PaasDeviceOptLog();
            deviceOptLog.setDeviceId(deviceBasicData.getCoreId());
            deviceOptLog.setDeviceName(deviceRpcRequest.getDeviceName());
            deviceOptLog.setType(DeviceOptTypeEnum.DEVICE_RPC.getCode());
            deviceOptLog.setContent(deviceRpcRequest.getCommand());
            deviceOptLog.setStatus(1);
            deviceOptLog.setTenantId(tenantId);
            deviceOptLog.setGmtModified(new Date());
            deviceOptLog.setGmtCreate(new Date());
            if(!deviceOptLogService.save(deviceOptLog)){
                log.error("deviceRpc optlog save error, deviceOptLog:{}", deviceOptLog);
            }
        }
        return OpenApiResult.success(true);
    }


    @PostMapping("/gw/delete")
    @ResponseBody
    public OpenApiResult deleteGw(HttpServletRequest request) {
        log.info("deleteGw ===> deviceDeleteRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DeviceDeleteRequest deviceDeleteRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DeviceDeleteRequest.class);

        if(deviceDeleteRequest ==null
                || StringUtils.isBlank(deviceDeleteRequest.getDeviceName())
        ){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"deviceName");
        }

        String token = request.getHeader("token");
        Map tokenPayload = JwtUtils.getPayload(token);
        String tenantId = (String) tokenPayload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("deleteGw tenantId is null,deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(deviceDeleteRequest.getDeviceName(), token);
        if(deviceBasicData==null){
            log.error("deleteGw deviceName:{} getDeviceByDeviceName type not found", deviceDeleteRequest.getDeviceName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
        }
        List<DeviceBasicData> gws = rexolarApiClient.getFromRelationsInfo(token, deviceBasicData.getCoreId());
        if(CollectionUtils.isEmpty(gws)){
            log.error("deleteGw gws is empty, deviceId:{}", deviceBasicData.getCoreId());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_GW_NOT_EXIST);
        }

        LambdaQueryWrapper<PaasGatewayCredentials> gwQuery = new LambdaQueryWrapper<>();
        gwQuery.eq(PaasGatewayCredentials::getGwName, deviceDeleteRequest.getDeviceName());
        gwQuery.eq(PaasGatewayCredentials::getTenantId, tenantId);
        gwQuery.eq(PaasGatewayCredentials::getStatus, GwStatusEnum.ON.getCode());
        List<PaasGatewayCredentials> gwList = gatewayCredentialsService.list(gwQuery);
        if(CollectionUtils.isEmpty(gwList)){
            log.error("deleteGw ILLEGAL_GW_NOT_EXIST, query:{}", gwQuery);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_GW_NOT_EXIST);
        }
        PaasGatewayCredentials paasGatewayCredentials = gwList.get(0);

        LambdaQueryWrapper<PaasGatewayDeviceRelation> query = new LambdaQueryWrapper<>();
        query.eq(PaasGatewayDeviceRelation::getGwId, paasGatewayCredentials.getGwId());
        query.eq(PaasGatewayDeviceRelation::getTenantId, tenantId);
        query.eq(PaasGatewayDeviceRelation::getStatus, GwDeviceStatusEnum.ON.getCode());
        List<PaasGatewayDeviceRelation> list = paasGatewayDeviceRelationService.list(query);
        if(!CollectionUtils.isEmpty(list)){
            for (PaasGatewayDeviceRelation gwDeviceRelation : list){
                boolean result = rexolarApiClient.deleteDevice(gwDeviceRelation.getDeviceId(), token);
                if(!result){
                    log.error("deleteGw error deleteDevice, deviceId:{}", gwDeviceRelation.getDeviceId());
                }
            }
        }
        paasGatewayDeviceRelationService.remove(query);

        DeviceBasicData basicData = rexolarApiClient.getDeviceInfo(paasGatewayCredentials.getGwId(), token);
            if(basicData==null){
            log.warn("deleteGw ILLEGAL_GW_NOT_EXIST, gwId:{}", paasGatewayCredentials.getGwId());
        }else {
            boolean result = rexolarApiClient.deleteDevice(paasGatewayCredentials.getGwId(), token);
            if(!result){
                log.error("deleteGw error deleteGw, gwId:{}", paasGatewayCredentials.getGwId());
            }
        }
            //TODO 网关解绑

        paasGatewayCredentials.setStatus(GwStatusEnum.DELETED.getCode());
        paasGatewayCredentials.setGmtModified(new Date());
        boolean updateResult = gatewayCredentialsService.updateById(paasGatewayCredentials);
        if(!updateResult){
            log.error("deleteGw error udpate paasGatewayCredentials, paasGatewayCredentials:{}", paasGatewayCredentials);
            return OpenApiResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
        }
        return OpenApiResult.success(true);
    }
    @PostMapping("/device/delete")
    @ResponseBody
    public OpenApiResult deleteDevice(HttpServletRequest request) {
        log.info("deleteDevice ===> deviceDeleteRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DeviceDeleteRequest deviceDeleteRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DeviceDeleteRequest.class);

        if(deviceDeleteRequest ==null
                || StringUtils.isBlank(deviceDeleteRequest.getDeviceName())
        ){
            log.error("deleteDevice 缺少必选参数, deviceDeleteRequest:{}", deviceDeleteRequest);
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS);
        }

        String token = request.getHeader("token");
        Map tokenPayload = JwtUtils.getPayload(token);
        String tenantId = (String) tokenPayload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("deviceRpc tenantId is null,deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }

        LambdaQueryWrapper<PaasGatewayDeviceRelation> query = new LambdaQueryWrapper<>();
        query.eq(PaasGatewayDeviceRelation::getDeviceName, deviceDeleteRequest.getDeviceName());
        query.eq(PaasGatewayDeviceRelation::getStatus, GwDeviceStatusEnum.ON.getCode());
        query.eq(PaasGatewayDeviceRelation::getTenantId, tenantId);
        List<PaasGatewayDeviceRelation> list = paasGatewayDeviceRelationService.list(query);
        if(CollectionUtils.isEmpty(list)){
            log.error("deleteDevice ILLEGAL_DEVICE_GW_NOT_EXIST, query:{}", deviceDeleteRequest.getDeviceName());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_GW_NOT_EXIST);
        }
        String gwId = list.get(0).getGwId();
        LambdaQueryWrapper<PaasGatewayCredentials> gwQuery = new LambdaQueryWrapper<>();
        gwQuery.eq(PaasGatewayCredentials::getGwId, gwId);
        List<PaasGatewayCredentials> gwList = gatewayCredentialsService.list(gwQuery);
        if(CollectionUtils.isEmpty(gwList)){
            log.error("deleteDevice ILLEGAL_GW_NOT_EXIST, query:{}", query);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_GW_NOT_EXIST);
        }
        DeviceBasicData basicData = rexolarApiClient.getDeviceInfo(list.get(0).getDeviceId(), token);
        if(basicData==null){
            log.error("deleteDevice ILLEGAL_DEVICE_NOT_EXIST, deviceId:{}", list.get(0).getDeviceId());
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_DEVICE_NOT_EXIST);
        }

        HashMap dataMap = new HashMap();
        dataMap.put("Version", "1.0");
        dataMap.put("VendorCode", "Rexense");
        String time = String.valueOf(System.currentTimeMillis());
        dataMap.put("Timestamp", time);
        dataMap.put("Seq", time);
        dataMap.put("DeviceId", gwList.get(0).getClientId());
        dataMap.put("FunctionCode", "DeleteDev");
        HashMap payload = new HashMap();
        payload.put("DeviceIds", Collections.singletonList(basicData.getName()));
        payload.put("Type", "0");
        dataMap.put("Payload", payload);

        boolean result = rexolarApiClient.updateDeviceAttributes(gwId, ApiConstant.SHARED_SCOPE, JSON.toJSONString(dataMap), token);
        if(!result){
            log.error("deleteDevice update gw attributes error, deviceRpcRequest:{}", deviceDeleteRequest);
        }

        result = rexolarApiClient.deleteDevice(list.get(0).getDeviceId(), token);
        if(!result){
            log.error("deleteDevice error, deviceRpcRequest:{}", deviceDeleteRequest);
        }else {
            PaasDeviceOptLog deviceOptLog = new PaasDeviceOptLog();
            deviceOptLog.setDeviceId(list.get(0).getDeviceId());
            deviceOptLog.setDeviceName(deviceDeleteRequest.getDeviceName());
            deviceOptLog.setType(DeviceOptTypeEnum.DEVICE_DELETE.getCode());
            deviceOptLog.setContent("delete device");
            deviceOptLog.setStatus(1);
            deviceOptLog.setGmtModified(new Date());
            deviceOptLog.setGmtCreate(new Date());
            if(!deviceOptLogService.save(deviceOptLog)){
                log.error("deleteDevice optlog save error, deviceOptLog:{}", deviceOptLog);
            }
        }

        return OpenApiResult.success(result);
    }

    @PostMapping("/device/log")
    @ResponseBody
    public OpenApiResult getDeviceLog(HttpServletRequest request) {
        log.info("getDeviceLog ===> deviceLogRequest:{}", OpenContextUtil.getContext().getParamsMap());
        DeviceLogRequest deviceLogRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), DeviceLogRequest.class);
        if(deviceLogRequest.getPageNo()==null || deviceLogRequest.getPageNo() < 0){
            deviceLogRequest.setPageNo(1);
        }
        if(deviceLogRequest.getPageSize()==null || deviceLogRequest.getPageSize()<= 0|| deviceLogRequest.getPageSize() > 100){
            deviceLogRequest.setPageSize(20);
        }
        String token = request.getHeader("token");
        Map tokenPayload = JwtUtils.getPayload(token);
        String tenantId = (String) tokenPayload.get("tenantId");
        if(StringUtils.isBlank(tenantId)){
            log.error("getDeviceLog tenantId is null,deviceRpcRequest:{}", OpenContextUtil.getContext().getParamsMap());
            return OpenApiResult.fail(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }
        try {
            long end = System.currentTimeMillis();
            long start = end  - ONE_DAY_SECONDS;
            if(StringUtils.isNotBlank(deviceLogRequest.getStartTime())){
                start = DateUtil.parse(deviceLogRequest.getStartTime(), "yyyy-MM-dd HH:mm:ss").getTime();
            }else {
                deviceLogRequest.setStartTime(DateUtil.format(new Date(start), "yyyy-MM-dd HH:mm:ss"));
            }
            if(StringUtils.isNotBlank(deviceLogRequest.getEndTime())){
                end = DateUtil.parse(deviceLogRequest.getEndTime(), "yyyy-MM-dd HH:mm:ss").getTime();
            }else {
                deviceLogRequest.setEndTime(DateUtil.format(new Date(end), "yyyy-MM-dd HH:mm:ss"));
            }

            if(start > end || end - start > ONE_DAY_SECONDS){
                log.error("getDeviceLog ILLEGAL_TIME_RANGE_OVERSIZE, deviceLogRequest:{}", deviceLogRequest);
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_TIME_RANGE);
            }
        }catch (Exception e){
            log.error("getDeviceLog ILLEGAL_TIME_FORMAT, deviceLogRequest:{}", deviceLogRequest);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_TIME_RANGE);
        }

        IPage<PaasDeviceOptLog> result = deviceOptLogService.selectPage(deviceLogRequest, tenantId);
        List<PaasDeviceOptLogResponse> responseList = new ArrayList<>();
        for(PaasDeviceOptLog paasDeviceOptLog : result.getRecords()){
            PaasDeviceOptLogResponse deviceOptLogResponse = new PaasDeviceOptLogResponse();
            BeanUtils.copyProperties(paasDeviceOptLog, deviceOptLogResponse);
            deviceOptLogResponse.setGmtCreate(DateUtil.format(paasDeviceOptLog.getGmtCreate(), "yyyy-MM-dd HH:mm:ss"));
            responseList.add(deviceOptLogResponse);
        }
        Page<PaasDeviceOptLogResponse> responsePage = new Page<>(deviceLogRequest.getPageNo(), deviceLogRequest.getPageSize());
        BeanUtils.copyProperties(result, responsePage);
        responsePage.setRecords(responseList);
        return OpenApiResult.success(responsePage);
    }

    @PostMapping("/profile/list")
    @ResponseBody
    public OpenApiResult getProfileList(HttpServletRequest request) {
        log.info("getProfileList ===> profileRequest:{}", OpenContextUtil.getContext().getParamsMap());
        ProfileRequest profileRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), ProfileRequest.class);
        String token = request.getHeader("token");
        List<DeviceProfileData> profileDataList = new ArrayList<>();
        List<DeviceProfileData> list = rexolarApiClient.getDeviceProfileInfos(token);
        for (DeviceProfileData deviceProfileData:list){
            if(StringUtils.isNotBlank(profileRequest.getProfileId()) && deviceProfileData.getProfileId().equals(profileRequest.getProfileId())){
            }else{
                if (StringUtils.isBlank(profileRequest.getName()) || deviceProfileData.getName().contains(profileRequest.getName())){
                    profileDataList.add(deviceProfileData);
                }
            }
        }
        return OpenApiResult.success(profileDataList);
    }

    @PostMapping("/gwTypeList")
    @ResponseBody
    public OpenApiResult gwTypeList(HttpServletRequest request) {
        log.info("gwTypeList ===> gwTypeRequest:{}", OpenContextUtil.getContext().getParamsMap());
        GwTypeRequest gwTypeRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), GwTypeRequest.class);
        String token = request.getHeader("token");
        List<DeviceProfileData> gwTypeList = rexolarApiClient.getGwTypeList(token);
        return OpenApiResult.success(gwTypeList);
    }

    @PostMapping("/alarm/list")
    @ResponseBody
    public OpenApiResult alarmList(HttpServletRequest request) {
        log.info("alarmList ===> alarmsPageRequest:{}", OpenContextUtil.getContext().getParamsMap());
        AlarmsPageRequest alarmsPageRequest = JSON.parseObject(JSON.toJSONString(OpenContextUtil.getContext().getParamsMap()), AlarmsPageRequest.class);

        if(StringUtils.isBlank(alarmsPageRequest.getStartTime())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"startTime");
        }
        if(StringUtils.isBlank(alarmsPageRequest.getEndTime())){
            return OpenApiResult.fail(ErrorCodeEnum.LESS_PARAMETERS.getCode(), ErrorCodeEnum.LESS_PARAMETERS.getMessage()+"endTime");
        }
        if(alarmsPageRequest.getPageNo()==null || alarmsPageRequest.getPageNo() < 0){
            alarmsPageRequest.setPageNo(0);
        }
        if(alarmsPageRequest.getPageSize()==null || alarmsPageRequest.getPageSize()<= 0|| alarmsPageRequest.getPageSize() > 100){
            alarmsPageRequest.setPageSize(20);
        }

        try {
            Long start = DateUtil.parse(alarmsPageRequest.getStartTime(), "yyyy-MM-dd HH:mm:ss").getTime();
            Long end = DateUtil.parse(alarmsPageRequest.getEndTime(), "yyyy-MM-dd HH:mm:ss").getTime();
            if(start > end || end - start > 24*60*60*1000){
                log.error("alarmList ILLEGAL_TIME_RANGE_OVERSIZE, deviceLogRequest:{}", alarmsPageRequest);
                return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_TIME_RANGE_OVERSIZE);
            }
        }catch (Exception e){
            log.error("alarmList ILLEGAL_TIME_FORMAT, deviceLogRequest:{}", alarmsPageRequest);
            return OpenApiResult.fail(ErrorCodeEnum.ILLEGAL_TIME_RANGE);
        }

        String token = request.getHeader("token");
        return OpenApiResult.success(rexolarApiClient.getAlarms(token, alarmsPageRequest));
    }
}
